<?php

namespace app\company\model;


use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

/**
 *  门店模型
 * @property  int $id
 * @property  int $company_id 公司id
 * @property  string $name 门店名称
 * @property  string $address 门店地址
 * @property  string $remark 备注
 * @property  int $status 状态
 * @property  int $racking_time 启用时间
 * @property  int sold_out_time 禁用时间
 */
class Store extends Base
{

    public static function onBeforeInsert(Store $model): void
    {
        $model->company_id   = getCompanyId();
        $model->racking_time = time();
    }

    public static function onAfterInsert(Store $model): void
    {
        // 添加用户
        $addUser                = request()->only(['real_name', 'mobile']);
        $addUser['store_id']    = $model->id;
        $addUser['company_id']  = $model->company_id;
        $addUser['is_salesman'] = 2;
        $user                   = StoreUser::create($addUser);
        //添加银行卡
        $add = request()->only(['user_name', 'bank_no', 'bank_type', 'bank_branch']);
        if ($add['user_name'] || $add['bank_no'] || $add['bank_type'] || $add['bank_branch']) {
            $add['store_id']      = $model->id;
            $add['store_user_id'] = $user->id;
            StoreUserBank::create($add);
        }
        //添加supplier_ids绑定关系
        if ($ids = request()->param('supplier_ids', '')) {
            $array = [];
            foreach (explode(',', $ids) as $id) {
                $add['supplier_id'] = $id;
                $add['store_id']    = $model->id;
                $add['company_id']  = $model->company_id;
                $array[]            = $add;
            }
            (new StoreSupplier())->saveAll($array);
        }
    }


    /**
     * @param Store $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public static function onBeforeUpdate(Store $model): void
    {
        //修改用户 余额
        $user = request()->only(['real_name', 'mobile', 'money']);
        if ($user['real_name'] || $user['mobile'] || $user['money']) {
            $userModel = StoreUser::where('store_id', $model->id)->find();
            if ($user['mobile']) {
                if (StoreUser::whereNotIn('id', $userModel->id)->where('mobile', $user['mobile'])->count()) {
                    throw new Exception('手机号已存在');
                }
            }
            $userModel->save($user);
        }
        //修改银行卡
        $bank = request()->only(['user_name', 'bank_no', 'bank_type', 'bank_branch']);
        if ($bank['user_name'] || $bank['bank_no'] || $bank['bank_type'] || $bank['bank_branch']) {
            $userId    = StoreUser::where('store_id', $model->id)->value('id');
            $bankModel = StoreUserBank::where('store_user_id', $userId)->find();
            if (!$bankModel) {
                $bankModel             = new StoreUserBank();
                $bank['store_id']      = $model->id;
                $bank['store_user_id'] = $userId;
            }
            $bankModel->save($bank);
        }
        //修改状态
        if ($status = request()->param('status', 0)) {
            if ($status == 1) $model->racking_time = time();
            if ($status == 2) $model->sold_out_time = time();
        }

        //修改supplier_ids绑定关系
        if ($ids = request()->param('supplier_ids', '')) {
            if ($model->storeSuppliers()->count())
                $model->storeSuppliers->delete();
            $array = [];
            foreach (explode(',', $ids) as $id) {
                $add['supplier_id'] = $id;
                $add['store_id']    = $model->id;
                $add['company_id']  = $model->company_id;
                $array[]            = $add;
            }
            (new StoreSupplier())->saveAll($array);
        }

    }

    /**
     * @param Store $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function onBeforeDelete(Store $model): void
    {

        if ($model->storeUsers()->count()) {
            //删除用户银行卡
            if ($model->storeUsers()->find()->StoreUserBanks()->count())
                $model->storeUsers()->find()->storeUserBanks->delete();
            //删除用户
            $model->storeUsers->delete();
            //删除门店关联第三方(经销商)
            if ($model->storeSuppliers()->count())
                $model->storeSuppliers->delete();
        }
    }
}